//  @ Project : GagalPanen
//  @ File Name : sprite.cpp
//  @ Date : 3/9/2011
//  @ Author : 
//
//

#include <vector>
#include "sprite.hpp"
#include "gamemaps.hpp"
#include "actiontype.hpp"
#include "direction.hpp"

Sprite::Sprite(GameInterface* game, int startX, int startY) :
    MovingCreature(game, game->getMaps()->getField()->getCellAt(startX, startY)),
    is_sleep_(true) {
  
}

Sprite::Sprite(GameInterface* game, std::ifstream& is) :
    MovingCreature(game, is),
    is_sleep_(true) {
  is >> is_sleep_;
}

void Sprite::save(std::ofstream& os) {
  MovingCreature::save(os);
  os << (int)is_sleep_ << std::endl;
}

Sprite::~Sprite() {}

void Sprite::advanceDay() {
  resetPosition();
}

void Sprite::advanceTime() {
  if (isSleep()) {
    return;
  }
  performSingleAction();
}

bool Sprite::isSleep() {
  return is_sleep_;
}

void Sprite::performSingleAction() {
  std::vector< ActionType > best;
  for (int x = 0; x < game_->getMaps()->getField()->getGrid()->getColumn(); ++x) {
    for (int y = 0; y < game_->getMaps()->getField()->getGrid()->getRow(); ++y) {
      Cell* cell = game_->getMaps()->getField()->getCellAt(x,y);
      if (isImportant(cell)) {
        for (int dir = 0; dir < DirectionNamespace::getDirectionCount(); ++dir) {
          Cell* target_cell = game_->getMaps()->getCellInFrontOff(cell, Direction(dir));
          if (game_->getMaps()->getField()->isReachable(
                  getCell(), getDirection(), target_cell,
                  DirectionNamespace::getTurnBack(Direction(dir)))) {
            std::vector< ActionType > actions =
                    game_->getMaps()->getField()->getShortestPathBetween(
                    getCell(), getDirection(), target_cell,
                    DirectionNamespace::getTurnBack(Direction(dir)));
            actions.push_back(getActionType());
            if ((int)best.size() == 0 || best.size() > actions.size()) {
              best = actions;
            }
          }
        }
      }
    }
  }
  if ((int)best.size() > 0) {
    performAction(best[0]);
  }
  return;
}

bool Sprite::isSteppable() {
  return isSleep();
}

void Sprite::wake() {
  is_sleep_ = false;
}

void Sprite::sleep() {
  is_sleep_ = true;
}

